

<!DOCTYPE html>
<html lang="zh-CN" data-default-color-scheme=auto>



<head>
  <meta charset="UTF-8">
  <link rel="apple-touch-icon" sizes="76x76" href="/img/favicon.png">
  <link rel="icon" href="/img/favicon.png">
  <meta name="viewport" content="width=device-width, initial-scale=1.0, maximum-scale=5.0, shrink-to-fit=no">
  <meta http-equiv="x-ua-compatible" content="ie=edge">
  
  <meta name="theme-color" content="#2f4154">
  <meta name="author" content="Fly542">
  <meta name="keywords" content="">
  
    <meta name="description" content="1. 概述 std::bind 函数定义在头文件中，是一个函数模板，它就像一个函数适配器，接受一个可调用对象（callable object），生成一个新的可调用对象来“适应”原对象的参数列表。一般而言，我们用它可以把一个原本接收N个参数的函数fn，通过绑定一些参数，返回一个接收M个（M可以大于N，但这么做没什么意义）参数的新函数。同时，使用std::bind函数还可以实现参数顺序调整等操作。 2">
<meta property="og:type" content="article">
<meta property="og:title" content="c++11 std::bind 详解">
<meta property="og:url" content="http://fly542.cn/2021/08/12/03%E8%BD%AF%E4%BB%B6%E5%BC%80%E5%8F%91/01c_cpp/12c11_bind%E8%AF%A6%E8%A7%A3/index.html">
<meta property="og:site_name" content="Fly542 技术沉淀">
<meta property="og:description" content="1. 概述 std::bind 函数定义在头文件中，是一个函数模板，它就像一个函数适配器，接受一个可调用对象（callable object），生成一个新的可调用对象来“适应”原对象的参数列表。一般而言，我们用它可以把一个原本接收N个参数的函数fn，通过绑定一些参数，返回一个接收M个（M可以大于N，但这么做没什么意义）参数的新函数。同时，使用std::bind函数还可以实现参数顺序调整等操作。 2">
<meta property="og:locale" content="zh_CN">
<meta property="article:published_time" content="2021-08-12T04:01:03.000Z">
<meta property="article:modified_time" content="2022-12-30T03:33:01.356Z">
<meta property="article:author" content="Fly542">
<meta property="article:tag" content="c++">
<meta property="article:tag" content="c11">
<meta name="twitter:card" content="summary_large_image">
  
  
  <title>c++11 std::bind 详解 - Fly542 技术沉淀</title>

  <link  rel="stylesheet" href="https://cdn.jsdelivr.net/npm/bootstrap@4/dist/css/bootstrap.min.css" />


  <link  rel="stylesheet" href="https://cdn.jsdelivr.net/npm/github-markdown-css@4/github-markdown.min.css" />
  <link  rel="stylesheet" href="https://cdn.jsdelivr.net/npm/hint.css@2/hint.min.css" />

  
    
    
      
      <link  rel="stylesheet" href="https://cdn.jsdelivr.net/npm/highlight.js@10/styles/github-gist.min.css" />
    
  

  
    <link  rel="stylesheet" href="https://cdn.jsdelivr.net/npm/@fancyapps/fancybox@3/dist/jquery.fancybox.min.css" />
  


<!-- 主题依赖的图标库，不要自行修改 -->

<link rel="stylesheet" href="//at.alicdn.com/t/font_1749284_ba1fz6golrf.css">



<link rel="stylesheet" href="//at.alicdn.com/t/font_1736178_lbnruvf0jn.css">


<link  rel="stylesheet" href="/css/main.css" />

<!-- 自定义样式保持在最底部 -->


  <script id="fluid-configs">
    var Fluid = window.Fluid || {};
    var CONFIG = {"hostname":"fly542.cn","root":"/","version":"1.8.14","typing":{"enable":true,"typeSpeed":70,"cursorChar":"_","loop":false},"anchorjs":{"enable":true,"element":"h1,h2,h3,h4,h5,h6","placement":"right","visible":"hover","icon":""},"progressbar":{"enable":true,"height_px":3,"color":"#29d","options":{"showSpinner":false,"trickleSpeed":100}},"copy_btn":true,"image_zoom":{"enable":true,"img_url_replace":["",""]},"toc":{"enable":true,"headingSelector":"h1,h2,h3,h4,h5,h6","collapseDepth":0},"lazyload":{"enable":true,"loading_img":"/img/loading.gif","onlypost":false,"offset_factor":2},"web_analytics":{"enable":false,"baidu":null,"google":null,"gtag":null,"tencent":{"sid":null,"cid":null},"woyaola":null,"cnzz":null,"leancloud":{"app_id":null,"app_key":null,"server_url":null,"path":"window.location.pathname","ignore_local":false}},"search_path":"/local-search.xml"};
  </script>
  <script  src="/js/utils.js" ></script>
  <script  src="/js/color-schema.js" ></script>
<meta name="generator" content="Hexo 6.0.0"></head>


<body>
  <header style="height: 70vh;">
    <nav id="navbar" class="navbar fixed-top  navbar-expand-lg navbar-dark scrolling-navbar">
  <div class="container">
    <a class="navbar-brand" href="/">
      <strong>Fly542 技术沉淀</strong>
    </a>

    <button id="navbar-toggler-btn" class="navbar-toggler" type="button" data-toggle="collapse"
            data-target="#navbarSupportedContent"
            aria-controls="navbarSupportedContent" aria-expanded="false" aria-label="Toggle navigation">
      <div class="animated-icon"><span></span><span></span><span></span></div>
    </button>

    <!-- Collapsible content -->
    <div class="collapse navbar-collapse" id="navbarSupportedContent">
      <ul class="navbar-nav ml-auto text-center">
        
          
          
          
          
            <li class="nav-item">
              <a class="nav-link" href="/">
                <i class="iconfont icon-home-fill"></i>
                首页
              </a>
            </li>
          
        
          
          
          
          
            <li class="nav-item">
              <a class="nav-link" href="/archives/">
                <i class="iconfont icon-archive-fill"></i>
                归档
              </a>
            </li>
          
        
          
          
          
          
            <li class="nav-item">
              <a class="nav-link" href="/categories/">
                <i class="iconfont icon-category-fill"></i>
                分类
              </a>
            </li>
          
        
          
          
          
          
            <li class="nav-item">
              <a class="nav-link" href="/tags/">
                <i class="iconfont icon-tags-fill"></i>
                标签
              </a>
            </li>
          
        
          
          
          
          
            <li class="nav-item">
              <a class="nav-link" href="/about/">
                <i class="iconfont icon-user-fill"></i>
                关于
              </a>
            </li>
          
        
        
          <li class="nav-item" id="search-btn">
            <a class="nav-link" target="_self" href="javascript:;" data-toggle="modal" data-target="#modalSearch" aria-label="Search">
              &nbsp;<i class="iconfont icon-search"></i>&nbsp;
            </a>
          </li>
        
        
          <li class="nav-item" id="color-toggle-btn">
            <a class="nav-link" target="_self" href="javascript:;" aria-label="Color Toggle">&nbsp;<i
                class="iconfont icon-dark" id="color-toggle-icon"></i>&nbsp;</a>
          </li>
        
      </ul>
    </div>
  </div>
</nav>

    <div class="banner" id="banner" parallax=true
         style="background: url('/img/default.png') no-repeat center center;
           background-size: cover;">
      <div class="full-bg-img">
        <div class="mask flex-center" style="background-color: rgba(0, 0, 0, 0.3)">
          <div class="page-header text-center fade-in-up">
            <span class="h2" id="subtitle" title="c++11 std::bind 详解">
              
            </span>

            
              <div class="mt-3">
  
  
    <span class="post-meta">
      <i class="iconfont icon-date-fill" aria-hidden="true"></i>
      <time datetime="2021-08-12 12:01" pubdate>
        2021年8月12日 中午
      </time>
    </span>
  
</div>

<div class="mt-1">
  
    <span class="post-meta mr-2">
      <i class="iconfont icon-chart"></i>
      6k 字
    </span>
  

  
    <span class="post-meta mr-2">
      <i class="iconfont icon-clock-fill"></i>
      
      
      50 分钟
    </span>
  

  
  
</div>

            
          </div>

          
        </div>
      </div>
    </div>
  </header>

  <main>
    
      

<div class="container-fluid nopadding-x">
  <div class="row nomargin-x">
    <div class="d-none d-lg-block col-lg-2"></div>
    <div class="col-lg-8 nopadding-x-md">
      <div class="container nopadding-x-md" id="board-ctn">
        <div class="py-5" id="board">
          <article class="post-content mx-auto">
            <!-- SEO header -->
            <h1 style="display: none">c++11 std::bind 详解</h1>
            
            <div class="markdown-body">
              <h2 id="1-概述"><a href="#1-概述" class="headerlink" title="1. 概述"></a>1. 概述</h2><p> std::bind 函数定义在头文件<functional>中，是一个函数模板，它就像一个函数适配器，接受一个可调用对象（callable object），生成一个新的可调用对象来“适应”原对象的参数列表。一般而言，我们用它可以把一个原本接收N个参数的函数fn，通过绑定一些参数，返回一个接收M个（M可以大于N，但这么做没什么意义）参数的新函数。同时，使用std::bind函数还可以实现参数顺序调整等操作。</p>
<h2 id="2-函数原型"><a href="#2-函数原型" class="headerlink" title="2. 函数原型"></a>2. 函数原型</h2><p>std::bind函数有两种函数原型，定义如下：</p>
<figure class="highlight stata"><table><tr><td class="gutter"><div class="code-wrapper"><pre><span class="line">1</span><br><span class="line">2</span><br></pre></div></td><td class="code"><pre><code class="hljs stata">template&lt; <span class="hljs-keyword">class</span> F, <span class="hljs-keyword">class</span>... <span class="hljs-keyword">Args</span> &gt; bind( F&amp;&amp; f, <span class="hljs-keyword">Args</span>&amp;&amp;... <span class="hljs-keyword">args</span> ); <br>template&lt; <span class="hljs-keyword">class</span> R, <span class="hljs-keyword">class</span> F, <span class="hljs-keyword">class</span>... <span class="hljs-keyword">Args</span> &gt;  bind( F&amp;&amp; f, <span class="hljs-keyword">Args</span>&amp;&amp;... <span class="hljs-keyword">args</span> );<br></code></pre></td></tr></table></figure>

<p>std::bind返回一个基于f的函数对象(obj)，调用obj时参数被绑定到args上。f的参数要么被绑定到具体的值，要么被绑定到 placeholders(占位符，如_1, _2, …, _n).</p>
<p>其中占位符<code>_1</code>,<code>_2</code>表示，当执行obj函数时的第1,第2 … 第n个参数。</p>
<h2 id="3-参数及用法解释"><a href="#3-参数及用法解释" class="headerlink" title="3. 参数及用法解释"></a>3. 参数及用法解释</h2><h3 id="3-1-参数"><a href="#3-1-参数" class="headerlink" title="3.1 参数"></a>3.1 参数</h3><p>f：一个可调用对象（可以是函数对象、函数指针、函数引用、成员函数指针、数据成员指针），它的参数将被绑定到args上。<br>args：绑定参数列表，参数会被值或占位符替换，其长度必须与f接收的参数个数一致。</p>
<figure class="highlight arduino"><table><tr><td class="gutter"><pre><span class="line">1</span><br><span class="line">2</span><br><span class="line">3</span><br><span class="line">4</span><br><span class="line">5</span><br></pre></td><td class="code"><pre><code class="hljs arduino">调用可调用对象时，绑定参数被std::move，调用参数被std::forward，你得根据可调用对象的行为来判断std::bind返回的函数对象是否可以多次调用。<br><br>绑定参数可以是bind表达式，占位符被替换为外层的调用参数，相当于用调用参数来调用这个bind表达式，求值后用来调用外层bind表达式——我是在读源码读到一半一脸懵逼的时候才知道这件事的。这与可调用对象被std::bind以后可以再std::bind并不冲突，因为bind表达式一个是作为绑定参数，另一个是作为可调用对象。<br><br>std::bind有个重载，可以用模板参数指定bind表达式的<span class="hljs-built_in"><span class="hljs-keyword">operator</span></span>()的返回类型。<br></code></pre></td></tr></table></figure>

<h3 id="3-2-调用形式"><a href="#3-2-调用形式" class="headerlink" title="3.2 调用形式"></a>3.2 调用形式</h3><p>调用std::bind的一般形式为：</p>
<figure class="highlight cpp"><table><tr><td class="gutter"><pre><span class="line">1</span><br></pre></td><td class="code"><pre><code class="hljs cpp"><span class="hljs-keyword">auto</span> newCallable = std::<span class="hljs-built_in">bind</span>(callable, arg_list);<br></code></pre></td></tr></table></figure>
<p>其中，newCallable 本身是一个可调用对象，arg_list 是一个逗号分隔的参数列表，对应给定的 callable 的参数。即，当我们调用 newCallable 时，newCallable 会调用callable，并传递给它 arg_list 中的参数。</p>
<h3 id="3-3-返回类型"><a href="#3-3-返回类型" class="headerlink" title="3.3 返回类型"></a>3.3 返回类型</h3><p>std::bind 的返回类型是一个函数对象,这个函数对象是一个未指定类型T的函数对象，这个函数对象的 std::is_bind_expression<T>::value == true；这个函数对象包含以下成员：</p>
<figure class="highlight cpp"><table><tr><td class="gutter"><pre><span class="line">1</span><br><span class="line">2</span><br><span class="line">3</span><br><span class="line">4</span><br><span class="line">5</span><br><span class="line">6</span><br><span class="line">7</span><br><span class="line">8</span><br><span class="line">9</span><br><span class="line">10</span><br><span class="line">11</span><br><span class="line">12</span><br><span class="line">13</span><br><span class="line">14</span><br><span class="line">15</span><br><span class="line">16</span><br></pre></td><td class="code"><pre><code class="hljs cpp"><span class="hljs-number">1.</span> 对象成员<br> 一个由std::forward&lt;F&gt;(f)构造而来的std::decay&lt;F&gt;::type类型的对象，一个对象的每一个参数类型都是由std::forward&lt;Arg_i&gt;(arg_i)构造而来的std::decay&lt;Arg_i&gt;::type。简单来说，std::decay&lt;F&gt;::type对象保存了调用std::bind时传递过来的f参数，而若干个std::decay&lt;Arg_i&gt;::type则保存了传递过来的args参数（一个std::decay&lt;Arg_i&gt;::type保存一个args）。<br><span class="hljs-number">2.</span> 构造函数<br> 如果T的所有对象成员都是可拷贝的，则它自身也是可拷贝的；如果它的所有对象成员都是可移动构造的，则它自身也是可移动构造的。<br><span class="hljs-number">3.</span> 成员类型 result_type（从C++<span class="hljs-number">17</span>开始result_type已经被弃用）<br>·如果F是函数指针或者成员函数指针，result_type就是F的返回值类型<br>·如果F是一个拥有（或者说定义了）result_type的类类型，那么T的result_type就是F::result_type，即使result_type已经在T中被定义过<br><span class="hljs-number">4.</span> 成员函数 <span class="hljs-built_in"><span class="hljs-keyword">operator</span></span>()<br> 这是最应该了解的，因为在实际使用过程中，我们调用std::bind得到的返回值就是用来作为函数调用的。<br> bind的返回值T，假设我们这样调用：<span class="hljs-built_in">g</span>(a1, a2, a3, … ai); 此时g内部保存的std::decay&lt;F&gt;::type类型的对象将被调用, 它将会按照如下的方式来为a1, a2, …, ai 绑定值。<br> · 如果调用bind时指定的是reference_wrapper&lt;T&gt;类型的，比如在调用bind时使用了std::ref 或者 std::cref来包装args，那么调用g内部的这个对象时，对应参数会以T&amp;类型传入std::decay&lt;F&gt;::type类型的对象.<br> · 如果在创建g时，使用了嵌套的bind，即g = <span class="hljs-built_in">bind</span>(fn, args…)的参数列表args中，存在某个arg：使得std::is_bind_expression&lt;<span class="hljs-keyword">decltype</span>(arg)&gt;::value == <span class="hljs-literal">true</span>, 那么这个嵌套的bind表达式会被立即调用，其返回值会被传给ret里的_MyFun作为参数(也就是说嵌套的bind返回值会被当做ret调用时的参数)， 如果嵌套的bind里用到了占位符placeholder, 这些placeholder将会从ret的调用参数<span class="hljs-built_in">ret</span>(a1, a2, … ai)中对应位置选择.<br> · 如果在创建g时，使用了占位符placeholders, 即 g = <span class="hljs-built_in">bind</span>(fn, arg1, arg2, …, _1, _2, …), (对于_1, _2…, 有std::is_placeholder&lt;T&gt;::value != <span class="hljs-number">0</span>). 那么a1, a2, …, ai会以转发的形式forward&lt;ai&gt;(ai)传递给_MyFun, a1对应_1, a2对应_2, 以此类推.<br> 否则，ret内部保存的args，即上文提到的_Mybargs(bind调用时绑定的参数们)将被以左值的形式传给_MyFun以完成调用，这些参数和g有相同cv限定属性.<br> 如果<span class="hljs-built_in">g</span>(a1, a2, …, ai)中，有哪些ai没有匹配任何的placeholders，比如在调用bind时，placeholder只有_1, 而<span class="hljs-built_in">g</span>(a1, a2, a3), 那么a2, a3就是没有匹配的，没有被匹配的参数将被求值，但是会被丢弃。<br> 如果g被指定为<span class="hljs-built_in"><span class="hljs-keyword">volatile</span></span>(<span class="hljs-keyword">volatile</span> <span class="hljs-keyword">or</span> <span class="hljs-keyword">const</span> <span class="hljs-keyword">volatile</span>)，结果是未定义的。<br></code></pre></td></tr></table></figure>

<h2 id="4-类成员函数回调"><a href="#4-类成员函数回调" class="headerlink" title="4 类成员函数回调"></a>4 类成员函数回调</h2><p>在c++中，常用的回调函数场景是，在一个类A中，有一个普通成员函数a,在类B中，有一个普通成员函数b,在b中，想要回调函数a，这才是c++回调函数的正确打开方式。</p>
<p>先上一段代码：</p>
<figure class="highlight cpp"><table><tr><td class="gutter"><pre><span class="line">1</span><br><span class="line">2</span><br><span class="line">3</span><br><span class="line">4</span><br><span class="line">5</span><br><span class="line">6</span><br><span class="line">7</span><br><span class="line">8</span><br><span class="line">9</span><br><span class="line">10</span><br><span class="line">11</span><br><span class="line">12</span><br><span class="line">13</span><br><span class="line">14</span><br><span class="line">15</span><br><span class="line">16</span><br><span class="line">17</span><br><span class="line">18</span><br><span class="line">19</span><br><span class="line">20</span><br><span class="line">21</span><br><span class="line">22</span><br><span class="line">23</span><br><span class="line">24</span><br><span class="line">25</span><br><span class="line">26</span><br><span class="line">27</span><br><span class="line">28</span><br><span class="line">29</span><br><span class="line">30</span><br><span class="line">31</span><br><span class="line">32</span><br><span class="line">33</span><br><span class="line">34</span><br><span class="line">35</span><br><span class="line">36</span><br><span class="line">37</span><br><span class="line">38</span><br></pre></td><td class="code"><pre><code class="hljs cpp"><span class="hljs-meta">#<span class="hljs-meta-keyword">include</span> <span class="hljs-meta-string">&lt;iostream&gt;</span></span><br> <br><span class="hljs-meta">#<span class="hljs-meta-keyword">include</span> <span class="hljs-meta-string">&lt;functional&gt;</span></span><br> <br><span class="hljs-keyword">using</span> <span class="hljs-keyword">namespace</span> std;<br><span class="hljs-keyword">using</span> <span class="hljs-keyword">namespace</span> std::placeholders;<br> <br><span class="hljs-keyword">typedef</span> std::function&lt;<span class="hljs-built_in"><span class="hljs-keyword">void</span></span>(<span class="hljs-keyword">int</span>,<span class="hljs-keyword">int</span>)&gt; Fun;<br> <br><span class="hljs-class"><span class="hljs-keyword">class</span> <span class="hljs-title">B</span>&#123;</span><br>	<span class="hljs-keyword">public</span>:<br>        <span class="hljs-function"><span class="hljs-keyword">void</span> <span class="hljs-title">call</span><span class="hljs-params">(<span class="hljs-keyword">int</span> a,Fun f)</span></span><br><span class="hljs-function">        </span>&#123;<br>            <span class="hljs-built_in">f</span>(a,<span class="hljs-number">2</span>);<br>        &#125;<br>&#125;;<br> <br><span class="hljs-class"><span class="hljs-keyword">class</span> <span class="hljs-title">Test</span>&#123;</span><br><span class="hljs-keyword">public</span>:<br>	<span class="hljs-function"><span class="hljs-keyword">void</span> <span class="hljs-title">callback</span><span class="hljs-params">(<span class="hljs-keyword">int</span> a,<span class="hljs-keyword">int</span> b)</span></span><br><span class="hljs-function">	</span>&#123;<br>        cout&lt;&lt;a&lt;&lt;<span class="hljs-string">&quot;+&quot;</span>&lt;&lt;b&lt;&lt;<span class="hljs-string">&quot;=&quot;</span>&lt;&lt;a+b&lt;&lt;endl;<br>	&#125;<br> <br>	<span class="hljs-function"><span class="hljs-keyword">void</span> <span class="hljs-title">bind</span><span class="hljs-params">()</span></span><br><span class="hljs-function">	</span>&#123;<br>        Fun fun=std::<span class="hljs-built_in">bind</span>(&amp;Test::callback,<span class="hljs-keyword">this</span>,_1,_2);<br>		B b;<br>		b.<span class="hljs-built_in">call</span>(<span class="hljs-number">1</span>,fun);<br>	&#125;<br> <br>&#125;;<br><span class="hljs-function"><span class="hljs-keyword">int</span> <span class="hljs-title">main</span><span class="hljs-params">()</span></span><br><span class="hljs-function"></span>&#123;<br>    Test test;<br>	test.<span class="hljs-built_in">bind</span>();<br>	<span class="hljs-keyword">return</span> <span class="hljs-number">0</span>;<br>&#125;<br></code></pre></td></tr></table></figure>

<p>上面的程序中，Test类中的bind函数调用B类中的call函数，b中的call函数又反过来回调Test类中的callback函数。记住function和bind都是c++11标准函数，编译的时候要加-std=c++11。</p>
<p>在分析上面程序之前，先介绍一下两个辅助函数，分别是bind函数和function函数，这两个函数之前是boost函数成员，现在加入到c++11标准中，使用更加方便。</p>
<h3 id="bind函数"><a href="#bind函数" class="headerlink" title="bind函数"></a>bind函数</h3><p>定义在头文件functional中。可以看成是对一个函数的改造器，可以借助于集合的观点来说（尽管可能没这回事），可以将bind函数看作是返回一个子函数。这个子函数可以是bind绑定的函数的子集，也可以是本身。</p>
<p> 一般常用语法是： newFunName=bind(oldFunName,arg_list);</p>
<p>bind函数返回一个新的函数对象。其中bind第一个参数是oldFunName,它是待绑定的函数名，arg_list是oldFunName的参数列表。注意，这个参数列表是旧函数的参数列表，前面提到，返回的是子函数。我们可以随便给子函数定几个参数，但是肯定不能多于bind所绑定的原函数的参数个数。举个例子：</p>
<figure class="highlight awk"><table><tr><td class="gutter"><pre><span class="line">1</span><br><span class="line">2</span><br><span class="line">3</span><br><span class="line">4</span><br></pre></td><td class="code"><pre><code class="hljs awk"><span class="hljs-regexp">//g</span>是一个有两个参数的可调用对象<br>auto g=bind(f,a,b,_2,c,_1);<br><span class="hljs-regexp">//</span>其中f是具有<span class="hljs-number">5</span>个参数的函数<br><span class="hljs-regexp">//</span>当我们调用g(x,y)时，实际调用的是f(a,b,y,c,x)<br></code></pre></td></tr></table></figure>

<p>在这个示例中，我们可能要调用f函数，并传入5个参数，但是我们现在调用g(x,y)，只要传入两个参数，同样能达到这个效果。当然，我费这么多事其实肯定不是为了省几个参数，主要还是为了将一个函数转化成一个可以作为回调的函数指针，可以看成是原函数指针的别名。</p>
<p>上面出现的_1，_2是它的占位符，bind最多可以使用9个占位符。这个占位符命名在std的placeholders中，使用时，要使用using std::placeholders.</p>
<h3 id="function函数"><a href="#function函数" class="headerlink" title="function函数"></a>function函数</h3><p> function是一个函数对象的<code>容器</code>。</p>
<p>如function&lt;int(int,int)&gt; fun;  fun是一个函数模板，可以接受两个int型参数，并返回一个int型参数。平时可以将它赋值给一个函数指针。</p>
<p>例如上面的回调函数： Fun fun=std::bind(&amp;Test::callback,this,_1,_2);</p>
<p>其中bind用于绑定一个Test类的callback函数，它有两个参数，在这里，因为它是一个类成员函数，中间传入一个this指针，另外两个_1和_2则是它的两个参数。bind返回一个函数指针，将它赋给fun,fun作为一个函数容器，容纳bind函数返回的临时函数指针。 这样就成功的将fun作为一个函数参数的别名，可以用于传给回调函数了。</p>
<p>关于bind和function函数，再举一个例子。</p>
<figure class="highlight cpp"><table><tr><td class="gutter"><pre><span class="line">1</span><br><span class="line">2</span><br><span class="line">3</span><br><span class="line">4</span><br><span class="line">5</span><br><span class="line">6</span><br><span class="line">7</span><br><span class="line">8</span><br><span class="line">9</span><br><span class="line">10</span><br><span class="line">11</span><br><span class="line">12</span><br><span class="line">13</span><br><span class="line">14</span><br><span class="line">15</span><br><span class="line">16</span><br><span class="line">17</span><br><span class="line">18</span><br><span class="line">19</span><br><span class="line">20</span><br><span class="line">21</span><br><span class="line">22</span><br><span class="line">23</span><br><span class="line">24</span><br><span class="line">25</span><br><span class="line">26</span><br><span class="line">27</span><br><span class="line">28</span><br><span class="line">29</span><br><span class="line">30</span><br><span class="line">31</span><br><span class="line">32</span><br><span class="line">33</span><br><span class="line">34</span><br><span class="line">35</span><br><span class="line">36</span><br><span class="line">37</span><br><span class="line">38</span><br><span class="line">39</span><br><span class="line">40</span><br><span class="line">41</span><br><span class="line">42</span><br><span class="line">43</span><br><span class="line">44</span><br><span class="line">45</span><br><span class="line">46</span><br><span class="line">47</span><br><span class="line">48</span><br><span class="line">49</span><br><span class="line">50</span><br><span class="line">51</span><br><span class="line">52</span><br><span class="line">53</span><br><span class="line">54</span><br></pre></td><td class="code"><pre><code class="hljs cpp"><span class="hljs-meta">#<span class="hljs-meta-keyword">include</span> <span class="hljs-meta-string">&lt;iostream&gt;</span>  </span><br><span class="hljs-meta">#<span class="hljs-meta-keyword">include</span> <span class="hljs-meta-string">&lt;functional&gt;</span>  </span><br><span class="hljs-keyword">using</span> <span class="hljs-keyword">namespace</span> std;  <br>  <br><span class="hljs-keyword">typedef</span> std::function&lt;<span class="hljs-built_in"><span class="hljs-keyword">void</span></span> ()&gt; fp;  <br><span class="hljs-function"><span class="hljs-keyword">void</span> <span class="hljs-title">g_fun</span><span class="hljs-params">()</span>  </span><br><span class="hljs-function"></span>&#123;  <br>    cout&lt;&lt;<span class="hljs-string">&quot;g_fun()&quot;</span>&lt;&lt;endl;  <br>&#125;  <br><span class="hljs-class"><span class="hljs-keyword">class</span> <span class="hljs-title">A</span>  </span><br><span class="hljs-class">&#123;</span>  <br><span class="hljs-keyword">public</span>:  <br>    <span class="hljs-function"><span class="hljs-keyword">static</span> <span class="hljs-keyword">void</span> <span class="hljs-title">A_fun_static</span><span class="hljs-params">()</span>  </span><br><span class="hljs-function">    </span>&#123;  <br>        cout&lt;&lt;<span class="hljs-string">&quot;A_fun_static()&quot;</span>&lt;&lt;endl;  <br>    &#125;  <br>    <span class="hljs-function"><span class="hljs-keyword">void</span> <span class="hljs-title">A_fun</span><span class="hljs-params">()</span>  </span><br><span class="hljs-function">    </span>&#123;  <br>        cout&lt;&lt;<span class="hljs-string">&quot;A_fun()&quot;</span>&lt;&lt;endl;  <br>    &#125;  <br>    <span class="hljs-function"><span class="hljs-keyword">void</span> <span class="hljs-title">A_fun_int</span><span class="hljs-params">(<span class="hljs-keyword">int</span> i)</span>  </span><br><span class="hljs-function">    </span>&#123;  <br>        cout&lt;&lt;<span class="hljs-string">&quot;A_fun_int() &quot;</span>&lt;&lt;i&lt;&lt;endl;  <br>    &#125;  <br>  <br>    <span class="hljs-comment">//非静态类成员，因为含有this指针，所以需要使用bind  </span><br>    <span class="hljs-function"><span class="hljs-keyword">void</span> <span class="hljs-title">init</span><span class="hljs-params">()</span>  </span><br><span class="hljs-function">    </span>&#123;  <br>        fp fp1=std::<span class="hljs-built_in">bind</span>(&amp;A::A_fun,<span class="hljs-keyword">this</span>);  <br>        <span class="hljs-built_in">fp1</span>();  <br>    &#125;  <br>  <br>    <span class="hljs-function"><span class="hljs-keyword">void</span> <span class="hljs-title">init2</span><span class="hljs-params">()</span>  </span><br><span class="hljs-function">    </span>&#123;  <br>        <span class="hljs-keyword">typedef</span> std::function&lt;<span class="hljs-built_in"><span class="hljs-keyword">void</span></span> (<span class="hljs-keyword">int</span>)&gt; fpi;  <br>        <span class="hljs-comment">//对于参数要使用占位符 std::placeholders::_1  </span><br>        fpi f=std::<span class="hljs-built_in">bind</span>(&amp;A::A_fun_int,<span class="hljs-keyword">this</span>,std::placeholders::_1);  <br>        <span class="hljs-built_in">f</span>(<span class="hljs-number">5</span>);  <br>    &#125;  <br>&#125;;  <br><span class="hljs-function"><span class="hljs-keyword">int</span> <span class="hljs-title">main</span><span class="hljs-params">()</span>  </span><br><span class="hljs-function"></span>&#123;  <br>    <span class="hljs-comment">//绑定到全局函数  </span><br>    fp f2=<span class="hljs-built_in">fp</span>(&amp;g_fun);  <br>    <span class="hljs-built_in">f2</span>();  <br>  <br>    <span class="hljs-comment">//绑定到类静态成员函数  </span><br>    fp f1=<span class="hljs-built_in">fp</span>(&amp;A::A_fun_static);  <br>    <span class="hljs-built_in">f1</span>();  <br>  <br>    <span class="hljs-built_in">A</span>().<span class="hljs-built_in">init</span>();  <br>    <span class="hljs-built_in">A</span>().<span class="hljs-built_in">init2</span>();  <br>    <span class="hljs-keyword">return</span> <span class="hljs-number">0</span>;  <br>&#125;<br></code></pre></td></tr></table></figure>
<h2 id="5-注意"><a href="#5-注意" class="headerlink" title="5 注意"></a>5 注意</h2><p>如可调用 (Callable) 中描述，<font color=#ff0000><code>调用指向非静态成员函数指针或指向非静态数据成员指针时，首参数必须是引用或指针</code></font>（可以包含智能指针，如 std::shared_ptr 与 std::unique_ptr），指向将访问其成员的对象。 </p>
<p>所以在调用类的成员函数的时候首参必须是this</p>
<h2 id="参考"><a href="#参考" class="headerlink" title="参考"></a>参考</h2><figure class="highlight awk"><table><tr><td class="gutter"><pre><span class="line">1</span><br><span class="line">2</span><br><span class="line">3</span><br><span class="line">4</span><br><span class="line">5</span><br></pre></td><td class="code"><pre><code class="hljs awk">https:<span class="hljs-regexp">//</span>blog.csdn.net<span class="hljs-regexp">/afei__/</span>article<span class="hljs-regexp">/details/</span><span class="hljs-number">81985937</span><br>https:<span class="hljs-regexp">//</span>blog.csdn.net<span class="hljs-regexp">/hyp1977/</span>article<span class="hljs-regexp">/details/</span><span class="hljs-number">51784520</span><br>https:<span class="hljs-regexp">//</span>en.cppreference.com<span class="hljs-regexp">/w/</span>cpp<span class="hljs-regexp">/utility/</span>functional/bind<br>https:<span class="hljs-regexp">//</span>www.cnblogs.com<span class="hljs-regexp">/jerry-fuyi/</span>p/<span class="hljs-number">12633621</span>.html<br>https:<span class="hljs-regexp">//</span>blog.csdn.net<span class="hljs-regexp">/xiexievv/</span>article<span class="hljs-regexp">/details/</span><span class="hljs-number">50517964</span><br></code></pre></td></tr></table></figure>
            </div>
            <hr>
            <div>
              <div class="post-metas mb-3">
                
                  <div class="post-meta mr-3">
                    <i class="iconfont icon-category"></i>
                    
                      <a class="hover-with-bg" href="/categories/%E8%BD%AF%E4%BB%B6%E5%BC%80%E5%8F%91/">软件开发</a>
                    
                  </div>
                
                
                  <div class="post-meta">
                    <i class="iconfont icon-tags"></i>
                    
                      <a class="hover-with-bg" href="/tags/c/">c++</a>
                    
                      <a class="hover-with-bg" href="/tags/c11/">c11</a>
                    
                  </div>
                
              </div>
              
                <p class="note note-warning">
                  
                    本博客所有文章除特别声明外，均采用 <a target="_blank" href="https://creativecommons.org/licenses/by-sa/4.0/deed.zh" rel="nofollow noopener noopener">CC BY-SA 4.0 协议</a> ，转载请注明出处！
                  
                </p>
              
              
                <div class="post-prevnext">
                  <article class="post-prev col-6">
                    
                    
                      <a href="/2021/12/22/04DevOps/13typora%E9%85%8D%E7%BD%AE%E6%A0%87%E9%A2%98%E8%87%AA%E5%8A%A8%E6%B7%BB%E5%8A%A0%E5%BA%8F%E5%8F%B7/">
                        <i class="iconfont icon-arrowleft"></i>
                        <span class="hidden-mobile">typora配置标题自动添加序号</span>
                        <span class="visible-mobile">上一篇</span>
                      </a>
                    
                  </article>
                  <article class="post-next col-6">
                    
                    
                      <a href="/2021/08/09/03%E8%BD%AF%E4%BB%B6%E5%BC%80%E5%8F%91/01c_cpp/11unique_ptr%E5%92%8Cshared_ptr%E5%8F%8Aweak_ptr%E7%9A%84%E4%BD%BF%E7%94%A8/">
                        <span class="hidden-mobile">unique_ptr和shared_ptr及weak_ptr的使用</span>
                        <span class="visible-mobile">下一篇</span>
                        <i class="iconfont icon-arrowright"></i>
                      </a>
                    
                  </article>
                </div>
              
            </div>

            
          </article>
        </div>
      </div>
    </div>
    
      <div class="d-none d-lg-block col-lg-2 toc-container" id="toc-ctn">
        <div id="toc">
  <p class="toc-header"><i class="iconfont icon-list"></i>&nbsp;目录</p>
  <div class="toc-body" id="toc-body"></div>
</div>

      </div>
    
  </div>
</div>

<!-- Custom -->


    

    
      <a id="scroll-top-button" aria-label="TOP" href="#" role="button">
        <i class="iconfont icon-arrowup" aria-hidden="true"></i>
      </a>
    

    
      <div class="modal fade" id="modalSearch" tabindex="-1" role="dialog" aria-labelledby="ModalLabel"
     aria-hidden="true">
  <div class="modal-dialog modal-dialog-scrollable modal-lg" role="document">
    <div class="modal-content">
      <div class="modal-header text-center">
        <h4 class="modal-title w-100 font-weight-bold">搜索</h4>
        <button type="button" id="local-search-close" class="close" data-dismiss="modal" aria-label="Close">
          <span aria-hidden="true">&times;</span>
        </button>
      </div>
      <div class="modal-body mx-3">
        <div class="md-form mb-5">
          <input type="text" id="local-search-input" class="form-control validate">
          <label data-error="x" data-success="v"
                 for="local-search-input">关键词</label>
        </div>
        <div class="list-group" id="local-search-result"></div>
      </div>
    </div>
  </div>
</div>
    

    
  </main>

  <footer class="text-center mt-5 py-3">
  <div class="footer-content">
     <a href="https://hexo.io" target="_blank" rel="nofollow noopener"><span>Hexo</span></a> <i class="iconfont icon-love"></i> <a href="https://github.com/fluid-dev/hexo-theme-fluid" target="_blank" rel="nofollow noopener"><span>Fluid</span></a> 
  </div>
  

  

  
</footer>


  <!-- SCRIPTS -->
  
  <script  src="https://cdn.jsdelivr.net/npm/nprogress@0/nprogress.min.js" ></script>
  <link  rel="stylesheet" href="https://cdn.jsdelivr.net/npm/nprogress@0/nprogress.min.css" />

  <script>
    NProgress.configure({"showSpinner":false,"trickleSpeed":100})
    NProgress.start()
    window.addEventListener('load', function() {
      NProgress.done();
    })
  </script>


<script  src="https://cdn.jsdelivr.net/npm/jquery@3/dist/jquery.min.js" ></script>
<script  src="https://cdn.jsdelivr.net/npm/bootstrap@4/dist/js/bootstrap.min.js" ></script>
<script  src="/js/events.js" ></script>
<script  src="/js/plugins.js" ></script>

<!-- Plugins -->


  <script  src="/js/local-search.js" ></script>



  
    <script  src="/js/img-lazyload.js" ></script>
  



  



  
    <script  src="https://cdn.jsdelivr.net/npm/tocbot@4/dist/tocbot.min.js" ></script>
  
  
    <script  src="https://cdn.jsdelivr.net/npm/@fancyapps/fancybox@3/dist/jquery.fancybox.min.js" ></script>
  
  
    <script  src="https://cdn.jsdelivr.net/npm/anchor-js@4/anchor.min.js" ></script>
  
  
    <script defer src="https://cdn.jsdelivr.net/npm/clipboard@2/dist/clipboard.min.js" ></script>
  






  <script  src="https://cdn.jsdelivr.net/npm/typed.js@2/lib/typed.min.js" ></script>
  <script>
    (function (window, document) {
      var typing = Fluid.plugins.typing;
      var title = document.getElementById('subtitle').title;
      
        typing(title);
      
    })(window, document);
  </script>















<!-- 主题的启动项 保持在最底部 -->
<script  src="/js/boot.js" ></script>


</body>
</html>
